<!--
  * 指标上报
  *
-->
<template>
  <a-modal
      :title="'支门指标调配（'+form.year+'）'"
       width="55%"
      :open="visibleFlag"
      @cancel="onClose,visibleFlag=false"
      :maskClosable="false"
      :destroyOnClose="true"
  >
    <div style="background: #ececec;padding: 10px">
    <a-card  :bordered="false">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span:3 }">
      <a-row>
        <a-col :span="24" style="padding-bottom: 20px">
          支门指标分配(已分配：<span style="color: #8c8c8c">{{ title.distributed }}</span>m³ 剩余：<span
            style="color: #67c23a"> {{ title.unDistributed }}</span>m³)
        </a-col>
        <a-col :span="24">
          <a-form-item label="支门" name="branchDoors">
            <a-select
                show-search
                :options="ceDianListOption"
                :filter-option="filterOption"
                :field-names="{ label: 'name', value: 'id'}"
                v-model:value="form.branchDoors"/>
          </a-form-item>
        </a-col>
        <a-col :span="24">
          <a-form-item label="用水指标m³" name="waterUseIndicators">
            <a-input-number style="width: 100%" v-model:value="form.waterUseIndicators" placeholder="用水指标"/>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
      <div style="text-align: center">
        <a-space>
          <a-button type="primary" @click="onSubmit">提交</a-button>
          <a-button @click="onClose">重置</a-button>
        </a-space>
      </div>
    </a-card>
      <a-card   :bordered="false" style="margin-top: 10px">
        <a-row>
          <a-col :span="24" style="padding-bottom: 20px">
            支门分配详细
          </a-col>
          <a-col :span="24">
            <a-table :scroll="{ y:170 }" :dataSource="dataSource" :columns="columns" :pagination=false>
              <template #bodyCell="{ text, record, column }">
                <template v-if="column.dataIndex === 'action'">
                  <div class="smart-table-operate">
                                <a-button @click="onDelete(record)" danger type="link">删除</a-button>
                  </div>
                </template>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-card>
    </div>
    <template #footer>

    </template>
  </a-modal>
</template>
<script setup>
import {reactive, ref, nextTick} from 'vue';
import _ from 'lodash';
import {message, Modal} from 'ant-design-vue';
import {SmartLoading} from '/@/components/framework/smart-loading';
import {waterIndexUniApi} from '/@/api/water/index/water-index-uni-api.js';
import {waterIndexGateApi} from '/@/api/water/gate/water-index-gate-api.js';
import {smartSentry} from '/@/lib/smart-sentry';
import {loginApi} from "/@/api/system/login-api.js";
import {theTypeOfPlan, typeOfWaterUsed} from "/@/views/water-management/water-index-uni/water-index-uni-const.js";

// ------------------------ 事件 ------------------------

const emits = defineEmits(['reloadList']);

// ------------------------ 显示与隐藏 ------------------------
// 是否显示
const visibleFlag = ref(false);
let gqId = ref(1)
let title = ref({
  distributed: '',
  unDistributed: ''
})
let ceDianListOption = ref([])
let ceDianListMap = ref({})

function show(rowData) {
  Object.assign(form, formDefault);
  if (rowData && !_.isEmpty(rowData)) {
    Object.assign(form, rowData);
  }
  visibleFlag.value = true;
  nextTick(() => {
    formRef.value.clearValidate();
  });
  getDafultData();
}

async function getDafultData() {
 await queryPage()
}
async function getTitle() {
  const titleRes = await waterIndexUniApi.selectBranchDoorIndexTotal({irrigationId: +form.irrigationId});
  title.value = Object.assign({}, titleRes.data)
  const ceDianList = await waterIndexGateApi.getOptionsCeDian({});
  if (ceDianList.data && ceDianList.data.length > 0) {
    ceDianListOption.value = ceDianList.data
    ceDianListOption.value.forEach(x=>{
      ceDianListMap.value[x.id]=x.name
    })
  }
}
async function queryPage() {
  getTitle()
  let params = {
    unitId: form.unitId, //灌区id
    pageNum: 1,
    pageSize: 500,
  }
  const pageList=await waterIndexGateApi.queryPage(params)
  dataSource.value=pageList.data.list.map(x=>{
    return{
      ...x,
      czId:ceDianListMap.value[x.czId],
    }
  })
}
function onClose() {
  form.branchDoors=undefined
  form.waterUseIndicators=undefined
}

// ------------------------ 表单 ------------------------

// 组件ref
const formRef = ref();

const formDefault = {
  id: undefined, //id
  irrigationId: undefined, //灌区id
  unitId: undefined, //单位id
  year: undefined, //年
  branchDoors: undefined, //支门
  waterUseIndicators: undefined, //用水指标

};

let form = reactive({...formDefault});

const rules = {
  branchDoors: [{required: true, message: '支门 必填'}],
  waterUseIndicators: [{required: true, message: '用水指标 必填'}],
};
//支门搜索
const filterOption = (input, option) => {
  return option.name.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};
// 点击确定，验证表单
async function onSubmit() {
  try {
    await formRef.value.validateFields();
    save();
  } catch (err) {
    message.error('参数验证错误，请仔细填写表单数据!');
  }
}

// 新建、编辑API
async function save() {
  SmartLoading.show();
  form.unitId= +form.unitId
  form.czId= +form.branchDoors
  form.czIndex= +form.waterUseIndicators
  form.id=null
  try {
      await waterIndexGateApi.add(form);
    queryPage()
    message.success('操作成功');
    emits('reloadList');
    onClose();
  } catch (err) {
    smartSentry.captureError(err);
  } finally {
    SmartLoading.hide();
  }
}
//------------------------表格-------------------------------------
const dataSource= ref([
])

 const  columns= [
   {
     dataIndex: "key",
     title: '序号',
     key: "key",
     align: "center",
     customRender: ({text, record, index}) => `${index + 1}`,
     width: 60,
   },

  {
    title: '支门',
    dataIndex: 'czId',
    key: 'czId',
  },
   {
     title: '指标量(m³)',
     dataIndex: 'czIndex',
     key: 'czIndex',
   },
   {
     title: '操作',
     dataIndex: 'action',
     fixed: 'right',
     align: 'center',
     width: 120,
   },
]
//确认删除
function onDelete(data) {
  Modal.confirm({
    title: '提示',
    content: '确定要删除吗?',
    okText: '删除',
    okType: 'danger',
    onOk() {
      requestDelete(data);
    },
    cancelText: '取消',
    onCancel() {
    },
  });
}

//请求删除
async function requestDelete(data) {
  SmartLoading.show();
  try {
    await waterIndexGateApi.delete(data.id);
    message.success('删除成功');
    queryPage();
  } catch (e) {
    smartSentry.captureError(e);
  } finally {
    SmartLoading.hide();
  }
}
defineExpose({
  show,
});
</script>
